<template>
  <div class="qa-wrapper">
    <div class="wrapper-header">
      <div class="switch">
        <!-- 筛选项 -->
        <el-select style="width: 300px" v-model="selectedStatus" placeholder="筛选任务状态" @change="fetchRecords">
          <el-option v-for="status in statusOptions" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
        <!-- 日期选择控件 -->
        <el-date-picker
          style="margin-left: 10px; width: 300px"
          v-model="selectedDate"
          type="date"
          :shortcuts="shortcuts"
          value-format="YYYY-MM-DD"
          placeholder="选择日期"
          @change="fetchRecords"
        />
      </div>
      <div class="search">
        <el-button @click="fetchRecords" type="primary">查询</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="currentTaskRecords" style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column type="expand">
        <template #default="props">
          <el-descriptions style="margin-left: 10px" title="任务详情" :column="2" border>
            <el-descriptions-item label="用户姓名">{{ props.row.username || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="用户手机">{{ props.row.phone || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="当前周期开始日期">{{
              props.row.periodStartDate || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="当前周期结束日期">{{
              props.row.periodEndDate || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="每期本金">{{ props.row.principal || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="每期利息">{{ props.row.interest || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="总还款金额">{{ props.row.totalAmount  || '暂无信息' }}<span v-if="calculateOverdueAmount(props.row) > 0"> + {{calculateOverdueAmount(props.row)  }}</span></el-descriptions-item>
            <el-descriptions-item label="逾期金额" v-if="props.row.overdueAmount && props.row.overdueAmount > 0">{{ props.row.overdueAmount || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="实际还款日期" v-if="props.row.actualRepaymentDate" >{{
              props.row.actualRepaymentDate || '暂无信息'
            }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="期数">
        <template #default="props">
            <span>第{{props.row.installmentNumber}}期 （共{{ props.row.totalWeekNum }}期）</span>
        </template>
      </el-table-column>
      <el-table-column label="总额" prop="totalAmount" >
      <template #default="props">
        {{ props.row.totalAmount}} <span v-if="calculateOverdueAmount(props.row) > 0"> + <el-tag type="danger">{{calculateOverdueAmount(props.row)}}逾期费用</el-tag></span>
      </template>
     </el-table-column>
     <template v-if="!isMobile">
      <el-table-column label="还款周期">
        <template #default="props">
          <div class="time">
            <el-timeline>
              <el-timeline-item color="#0bbd87">{{ props.row.periodStartDate }}</el-timeline-item>
              <el-timeline-item :color="props.row.status === 'PAID' ? '#0bbd87' : 'red'">{{ props.row.periodEndDate }}</el-timeline-item>
            </el-timeline>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="props">
          <template v-if="isOverdue(props.row)">
            <el-tag type="danger">已逾期</el-tag>
          </template>
          <el-tag v-else :type="getStatusTag(props.row.status)">{{ getStatusLabel(props.row.status) }}</el-tag>
        </template>
      </el-table-column>
    </template>
    <template v-else >
      <el-table-column label="状态">
        <template #default="props">
          <template v-if="isOverdue(props.row)">
            <el-tag type="danger">已逾期</el-tag>
          </template>
          <el-tag v-else :type="getStatusTag(props.row.status)">{{ getStatusLabel(props.row.status) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="还款周期" :width="isMobile ? '150': undefined">
        <template #default="props">
          <div class="time">
            <el-timeline>
              <el-timeline-item color="#0bbd87">{{ props.row.periodStartDate }}</el-timeline-item>
              <el-timeline-item :color="props.row.status === 'PAID' ? '#0bbd87' : 'red'">{{ props.row.periodEndDate }}</el-timeline-item>
            </el-timeline>
          </div>
        </template>
      </el-table-column>
    </template>

    </el-table>
    <el-pagination
      style="margin-left: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="sizes, prev, pager, next, jumper"
      :total="total"
    />
  </div>
</template>
<style scoped>
@import '../style/taskList.less';
</style>
<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ApplyModule } from '@/services/modules/apply' // 请根据实际路径修改
import { isOverdue, calculateOverdueAmount } from '@/utils/helper' // 请根据实际路径修改
import * as httpService from '@/services/apply.service'

// 任务记录
const taskRecords = ref<ApplyModule.TaskVo[]>([])
const currentTaskRecords = ref<ApplyModule.TaskVo[]>([])
const selectedStatus = ref('')
const selectedDate = ref<string | undefined>(undefined)
// 检测是否为移动端
const isMobile = ref(false)
const checkIsMobile = () => {
  const userAgent = navigator.userAgent.toLowerCase()
  const mobileKeywords = ['android', 'iphone', 'ipad', 'ipod']
  return mobileKeywords.some(keyword => userAgent.includes(keyword))
}

const tableRowClassName = computed(() => {
  return 'success-row'
})

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '未还款', value: 'UNPAID' },
  { label: '已还款', value: 'PAID' },
  { label: '逾期', value: 'OVERDUE' },
]

const shortcuts = [
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '今天',
    value: () => {
      const date = new Date()
      return date
    },
  },
  {
    text: '明天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '后天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
      return date
    },
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(true)

// 获取状态文本
const getStatusLabel = (cellValue: string) => {
  const option = statusOptions.find((s) => s.value === cellValue)
  return option ? option.label : '未知'
}

// 获取状态颜色
const getStatusTag = (status: string) => {
  const statusMap = {
    UNPAID: 'warning',
    PAID: 'success',
    OVERDUE: 'danger',
  } as any
  return statusMap[status] || 'info'
}


// 获取任务记录
const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await httpService.searchMyTaskRecords({
      name: '',
      phone: '',
      status: selectedStatus.value,
      page: currentPage.value - 1,
      size: pageSize.value,
      dateTime: selectedDate.value,
    })
    
    const pageData = response.data
    taskRecords.value = pageData.list
    currentPage.value = pageData.currentPage
    pageSize.value = pageData.pageSize
    total.value = pageData.total
    currentTaskRecords.value = taskRecords.value
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message || '获取任务记录失败，请稍后重试')
    } else {
      ElMessage.error('获取任务记录失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 分页相关方法
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  handleCurrentChange(1)
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  fetchRecords()
}

onMounted(() => {
  isMobile.value = checkIsMobile()
  selectedStatus.value = ''
  selectedDate.value = undefined
  fetchRecords()
})
</script>
